﻿using System;

namespace BorgExt.Startup
{
    [Slot("Application", AutoOpen = false), Extension, Slot("Discoverer", AutoOpen = false)]
    public class Startup : ExtensionBase, IStartup
    {
        private static void ApplicationPlugged(CompositionEventArgs args)
        {
            ((IApplication)args.Plug.Extension.Object).Start();
        }

        private void DiscoveryPlugged(CompositionEventArgs args)
        {
            var discoverer = (IDiscoverer)args.Plug.Extension.Object;

            discoverer.Discovered += DiscoveryCore.AssemblyDiscovered;
            discoverer.Changed += DiscoveryCore.AssemblyDiscovered;
            discoverer.Removed += DiscoveryCore.AssemblyRemoved;

            discoverer.Start(DiscoveryCore.TypeBuilder);
        }

        private void DiscoveryUnplugged(CompositionEventArgs args)
        {
            var discoverer = (IDiscoverer)args.Plug.Extension.Object;

            discoverer.Discovered -= DiscoveryCore.AssemblyDiscovered;
            discoverer.Changed -= DiscoveryCore.AssemblyDiscovered;
            discoverer.Removed -= DiscoveryCore.AssemblyRemoved;
        }

        public void Start(DiscoveryCore discoveryCore)
        {
            if (discoveryCore == null)
                throw new ArgumentNullException("discoveryCore");

            DiscoveryCore = discoveryCore;

            var dscSlot = Slots["Discoverer"];
            dscSlot.Plugged += DiscoveryPlugged;
            dscSlot.Unplugged += DiscoveryUnplugged;
            dscSlot.Open();

            var appSlot = Slots["Application"];
            appSlot.Plugged += ApplicationPlugged;
            appSlot.Open();

            if (dscSlot.PluggedPlugs.Count == 0 && appSlot.PluggedPlugs.Count == 0)
                Runtime.Shutdown();
        }

        private DiscoveryCore DiscoveryCore { get; set; }
    }
}

